package cn.hou.lucene01;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queries.function.valuesource.LongFieldSource;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class FirstLucene {
    //创建索引
    @Test
    public void testIndex() {
        IndexWriter writer = null;
        // 1 指定索引库存放路径
        // 硬盘路径
        try {
            File indexrepository_file = new File("D:\\others\\lucene\\index");
            Path path = indexrepository_file.toPath();
            Directory directory = null;
            directory = FSDirectory.open(path);
            // 索引建立在内存中
            //Directory directory01=new RAMDirectory();
            // 2 创建writer
            //指定一个分词器
            Analyzer analyzer = new IKAnalyzer();//使用IK
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            writer = new IndexWriter(directory, config);
            // 3 创建document对象,并添加Filed域属性
            Document doc = null;
            File f = new File("D:\\others\\lucene\\doc");//文档目录
            for (File file : f.listFiles()) {//遍历每个文档
                doc = new Document();
                TextField textField = new TextField("fileName", file.getName(), Store.YES);
                //文件名
                doc.add(textField);
                //大小,数字类型使用point添加到索引中,同时如果需要存储,由于灭有Stroe,所以需要再创建一个StoredField进行存储
                // 即 IntPoint,DoublePoint等
                doc.add(new LongPoint("fileSize", file.length()));
                //大小
                doc.add(new StoredField("fileSize", file.length()));
                //同时添加排序支持
                doc.add(new NumericDocValuesField("fileSize", file.length()));
                //路径
                doc.add(new StoredField("filePath", file.getPath()));
                //内容
                doc.add(new TextField("fileContent", FileUtils.readFileToString(file), Store.NO));
                //doc.add(new TextField("fileContent",new FileReader(file)));
                // 4 使用indexWriter将doc对象写入索引库,此过程创建索引,并将索引和文档对象写入索引库
                writer.addDocument(doc);
            }
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //查找索引
    @Test
    public void test02() {
        try {
            File indexrepository_file = new File("D:\\others\\lucene\\index");
            Path path = indexrepository_file.toPath();
            Directory directory = FSDirectory.open(path);
            //创建IndexReader
            IndexReader ir = DirectoryReader.open(directory);
            System.out.println("max num:" + ir.maxDoc());
            System.out.println("index num:" + ir.numDocs());
            // 删除了的索引数 4.X版本后取消了恢复删除
            System.out.println("delete index num:" + ir.numDeletedDocs());
            ir.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testSearch() {
        try {
            //1 创建Directory对象,索引存放位置
            File indexrepository_file = new File("D:\\others\\lucene\\index");
            Path path = indexrepository_file.toPath();
            Directory directory = FSDirectory.open(path);
            //2 创建IndexReader
            IndexReader indexReader = DirectoryReader.open(directory);
            //3 创建IndexSearch对象
            IndexSearcher indexSearch = new IndexSearcher(indexReader);
            //4 创建TermQuery对象,指定查询的域和关键字
            Query query = new TermQuery(new Term("fileContent", "姚振"));
            //5 查询
            TopDocs topDocs = indexSearch.search(query, 5);//前5个
            //6 遍历结果
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;//文档id数组
            for (ScoreDoc scoreDoc : scoreDocs) {
                //根据id获取文档
                Document doc = indexSearch.doc(scoreDoc.doc);
                //获取结果,没有存储的是null,比如内容
                System.out.println("文档名: " + doc.get("fileName"));
                System.out.println("文档路径: " + doc.get("filePath"));
                System.out.println("文档大小: " + doc.get("fileSize"));
                System.out.println("文档内容: " + doc.get("fileContent"));
                System.out.println("-------------------");
            }
            //7 关闭reader
            indexReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
